package com.lu.bio;

import cn.hutool.core.util.StrUtil;

import java.net.*;

/**
 * @program lu-netty
 * @description: 模仿netty框架的 - 适配器
 * @author: zhanglu
 * @create: 2022-06-09 14:37:00
 */
public abstract class ChannelAdapter extends Thread{

    private Socket socket;
    private String charset;
    protected ChannelHandler ctx;

    public ChannelAdapter(Socket socket, String charset){
        this.socket = socket;
        this.charset = charset;
        while (!socket.isConnected()){
            break;
        }
        ctx = new ChannelHandler(this.socket, this.charset);
        channelActive();
    }

    public ChannelHandler ctx(){
        return this.ctx;
    }

    /**
     * 模版方法
     */
    @Override
    public void run() {
        try {
            while (true){
                String res = ctx.in().readLine();
                if(StrUtil.isEmpty(res)){
                    break;
                }
                channelRead(res);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ctx.close();
        }
    }

    //连接通知 - 处理器
    protected abstract void channelActive();

    //读取消息 - 处理器
    protected abstract void channelRead(Object msg);

}
